<?php
namespace App\Http\Controllers\desktop\publics;

use App\Models\Category;
use App\Models\Book;
use Illuminate\Support\Facades\Session;
use App\Models\Section;
use Illuminate\Support\Facades\Input;
use App\Models\Link;

class DefaultController extends BaseController {
	
	public function index() {
		$links = Link::select(['name', 'link'])
				->where('enable', '1')
				->orderBy('order', 'ASC')
				->get();
		$categories = Category::select(['id', 'name', 'order'])->get();
		$datas = [];
		foreach ($categories as $category) {
			$books = Book::where('category_id', $category->id)
					->orderBy('clicks', 'DESC')
					->take(9)
					->get();
			if($books->count() < 9) {
				continue;
			}
			$datas[] = [
				'category' => $category,
				'books' => $books
			];
		}
		return view('desktop.publics.index', compact('datas', 'links'));
	}
	
	public function history() {
		$bookIds = Session::all();
		$books = [];
		foreach ($bookIds as $key => $value) {
			$book = Book::find($key);
			if(!empty($book)) {
				$section = Section::where('order', (int)$value)->first();
				$books[] = [
					'book' => $book,
					'section' => $section
				];
			}
		}
		$hotBooks = Book::orderBy('likes', 'desc')->take(5)->get();
		return view('desktop.publics.history', compact('books', 'hotBooks'));
	}
	
	public function search() {
		$keywords = Input::get('keywords');
		$sort = Input::get('sort', 'likes');
		
		$books = Book::where('name', 'like', '%'.$keywords.'%');
		if(!is_null($sort)) {
			$books = $books->orderBy($sort, 'DESC');
		}
		$books = $books->take(10)->get();
		$hotBooks = Book::orderBy('clicks', 'desc')->take(5)->get();
		return view('desktop.publics.search', compact('keywords', 'sort', 'books', 'hotBooks'));
	}
}
